import nodemailer from 'nodemailer'
import { Response } from 'express'
import RedisServer from "./redis";
interface IEmail {
    service: string
    port: number
    secureConnection: boolean
    auth: {
        user: string
        pass: string
    }
}

export const EMAIL: IEmail = {
    service: String(process.env.NODE_EMAIL_SERVICE),   // 使用163邮箱
    port: Number(process.env.NODE_EMAIL_PORT), // 对于SSL连接，端口通常是465
    secureConnection: true, // 使用SSL
    auth: {
        user: String(process.env.NODE_EMAIL_USER), // 邮箱账号
        pass: String(process.env.NODE_EMAIL_PASS)    // 邮箱授权码
    }
}

interface IEmailResponse {
    code: number
    message: string
    data: any
}
// 创建邮件发送的配置
const transporter = nodemailer.createTransport(EMAIL);

// 生成code验证码
function generateCaptcha(length: number) {
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    let captcha = '';
    for (let i = 0; i < length; i++) {
        captcha += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return captcha;
}

const emailSync = (res: Response, email: string, mode: string): void => {
    const code = generateCaptcha(6)
    // 发送邮件
    return  transporter.sendMail({
        from: String(process.env.NODE_EMAIL_USER), // 发送者
        to: email, // 接收者
        subject: process.env.NODE_EMAIL_TITLE, // 邮件主题
        text: '邮件内容', // 邮件内容
        html: '<div>' +
            '<div>您的验证码为：' +
            '<div><center style="font-size: 18px;font-weight: bold;margin-top: 10px">' + code + '</center></div><div style="margin-top: 20px">有效期为五分钟,切勿泄露</div>' +
            '</div></div>', // 邮件内容，支持HTML
    }, async (error: any, info: any) => {
        const response: IEmailResponse = error ? { code: 500, message: '失败', data: error } : { code: 200, message: '成功', data: info }
        await RedisServer.redisSet(`code:${email}`, JSON.stringify({ mode, code }), 5 * 60)
        res.send(response)
    });
}

const emailSend = (res: Response, email: string, mode: string) => {
    return emailSync(res, email, mode)
}

export default emailSend